<template>
  <div class="upload">
    <el-upload
      class="avatar-uploader"
      action="https://yinzhi-hello.oss-cn-guangzhou.aliyuncs.com"
      :data="dataObj"
      :show-file-list="false"
      :on-success="handleAvatarSuccess"
      :before-upload="beforeAvatarUpload"
    >
      <img v-if="imageUrl" :src="imageUrl" class="avatar" />
      <i v-else class="el-icon-plus avatar-uploader-icon"></i>
      <div slot="tip" class="el-upload__tip">只能上传jpg文件，且不超过10MB</div>
    </el-upload>
  </div>
</template>

<script>
import ossApi from "@/api/oss";
import { getUUID } from "@/utils/request";

export default {
  name: "AvaUpload",
  components: {},

  props: ['fileName'],


  data() {
    return {
      dataObj: {
        policy: "",
        signature: "",
        key: "",
        ossaccessKeyId: "",
        dir: "",
        host: ""
      },
      imageUrl: null,
    };
  },

  methods: {
    emitInput(val) {
        this.$emit('input', val)
      },

    beforeAvatarUpload(file) {
      let _self = this;
      return new Promise((resolve, reject) => {
        ossApi.policy(_self.dataObj).then(response => {
            console.log("请求数据。。。。", response);
            console.log("fileName",this.fileName)
            _self.dataObj.policy = response.data.policy;
            _self.dataObj.signature = response.data.signature;
            _self.dataObj.ossaccessKeyId = response.data.accessid;
            _self.dataObj.key =response.data.dir + this.fileName + "/" + getUUID() + "_${filename}";
            _self.dataObj.dir = response.data.dir;
            _self.dataObj.host = response.data.host;
            console.log("响应数据。。。。", _self.dataObj);
            resolve(true);
          })
          .catch(error => {
            reject(false);
          });
      });
    },

    handleAvatarSuccess(res, file) {
      this.imageUrl =
        this.dataObj.host +
        "/" +
        this.dataObj.key.replace("${filename}", file.name);
        this.emitInput(this.imageUrl);
    }
  }
};
</script>

<style lang="scss" scoped>
el-upload {
  border: 1px dashed #8c939d
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
